<script setup>
import { ref } from 'vue'
import axios from "@/utils/request.js";
import {ElMessage, ElMessageBox} from 'element-plus'
import { onMounted } from "vue";
import {
  userAddBatchService,
  userAddService,
  userDeleteService,
  userExportService,
  userImportService,
  userModifyService,
  userPageService
} from "@/api/user.js";
import { useAdminStore } from '@/store/admin';
import { adminAddService,adminModifyService,adminSelectService } from '@/api/admin'

const adminStore = useAdminStore()
// 分页查询
const userInfo = ref([])
const selectIds = Array

const formatGender = (gender) => {
  switch (gender) {
    case 1:
      return '男';
    case 2:
      return '女';
    default:
      return '未知';
  }
};

const handleSelectionChange = (selection) => {
  selectIds.value = selection.map(item => item.userId)
}

//分页查询底部导航栏
const pageNo = ref(1)
const pageSize = ref(10)
const userIdInput = ref()
const nameInput = ref()
const gradeInput = ref()
const total = ref(0)

//页面加载的时候发送一次查询请求
onMounted(() => {
  load()
})
const handleCurrentChange = (val) => {
  pageNo.value = val
  load()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  load()
}
//发送分页查询请求（包括搜索功能）
const load = async () => {
  const res = await userPageService(
    pageNo.value,pageSize.value,userIdInput.value,nameInput.value,gradeInput.value
  )
  if(res.data.status === 'success'){
    userInfo.value = res.data.data.list
    total.value = res.data.data.totalCount
    userInfo.value.map(async item => {
      //根据userId查询admin信息
      const adminRes = await adminSelectService(item.userId)
      if(adminRes.data.status === 'success'){
        if(adminRes.data.data.totalCount == 1){
          item.role = adminRes.data.data.list[0].role
        }else{
          item.role = 5
        }
      }
    })
    console.log(userInfo.value)
  }else{
    ElMessage.error(res.data.info)
  }
}

/**
 * 添加队员
 */
//定义模态窗口变量和表格对象
const showAddModal = ref(false)
const userAddForm = ref({
  userId: '',
  name: '',
  gender: '0',
  email: '',
  telphoneNumber: '',
})
//打开模态窗口
const openAddModal = () => {
  //清空对象内容
  userAddForm.value = {
    userId: '',
    name: '',
    gender: '0',
    email: '',
    telphoneNumber: '',
  }
  showAddModal.value = true
}
//定义校验规则变量
const ruleFormRef = ref()
const rules = {
  userId: [
    {required: true, message: '请输入队员学号', trigger: 'blur'},
    {min: 12, max: 12, message: '队员学号必须为12位', trigger: 'blur'}
  ],
  name: [
    {required: true, message: '请输入队员姓名', trigger: 'blur'}
  ],
  grade: [
    {required: true, message: '请输入队员年级，示例：2023/2024', trigger: 'blur'},
    {min: 4, max: 4, message: '队员年级必须为4位', trigger: 'blur'}
  ]
}
//发送添加队员请求
const addUserInfo = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async(valid) => {
    if (valid) {
      if(userAddForm.value.gender == '')userAddForm.value.gender = '0'
      const res = await userAddService(userAddForm.value)
      if(res.data.status === 'success'){
        await load()
        ElMessage.success('添加成员成功')
      }else{
        ElMessage.error(res.data.info)
        // ElMessage.error('队员学号不能重复')
      }
      showAddModal.value = false
      showAddModal.value.userId= ''
      showAddModal.value.name= ''
      showAddModal.value.grade= ''
      showAddModal.value.gender= ''
      showAddModal.value.telphoneNumber= ''
      ruleFormRef.value.resetFields()
    }
  })
}

/**
 * 修改队员信息
 * @type {Ref<UnwrapRef<boolean>, UnwrapRef<boolean> | boolean>}
 */
//修改队员（弹出模态窗口）
//定义模态窗口变量和表格对象
const showModifyModal = ref(false)
const userForm = ref({
  userId: '',
  name: '',
  gender: '',
  email: '',
  telphoneNumber: '',
})
const openModifyModal = (userInfo) => {
  //将队员数据渲染到模态窗口的表格上面
  userForm.value.userId = userInfo.userId
  userForm.value.name = userInfo.name
  userForm.value.gender = userInfo.gender
  userForm.value.email = userInfo.email
  userForm.value.telphoneNumber = userInfo.telphoneNumber
  //打开模态窗口
  showModifyModal.value = true
}

//发送修改队员请求
const handleEdit = async() => {
  const res = await userModifyService(userForm.value)
  if(res.data.status === 'success'){
    await load()
    ElMessage.success('修改队员信息成功')
  }else{
    ElMessage.error(res.data.info)
  }
  showModifyModal.value = false
}

/**
 * 删除队员
 */
const openDeleteModal = (userId) => {
  ElMessageBox.confirm(
    '确定要删除该队员吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const userIds = Array.of(userId)
      const res = await userDeleteService(userIds)
      if(res.data.status === 'success'){
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }else{
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
      await load()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
/**
 * 批量删除队员
 */
const opendeleteAllModal = () => {
  //非空判断
  if(selectIds.value == null){
    ElMessage.info('未选中任何一名队员')
    return
  }
  if(selectIds.value != null && selectIds.value.length === 0){
    ElMessage.info('未选中任何一名队员')
    return
  }
  //批量删除
  ElMessageBox.confirm(
    '确定要删除所有选中的队员吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const res = await userDeleteService(selectIds.value)
      if(res.data.status === 'success'){
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }else{
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
      load()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

/**
 * 导出excel表格
 */
const exportExcel = async() => {
  const res = await userExportService(pageNo.value,pageSize.value,userIdInput.value,nameInput.value,gradeInput.value)
  if(res.status === 200){
     // 创建Blob对象
     const file = new Blob([res.data], { type: res.data.type });
    // 创建URL对象
    const fileURL = URL.createObjectURL(file);
    // 创建一个隐藏的a标签并设置属性
    const link = document.createElement('a');
    link.href = fileURL;
    link.setAttribute('download', 'user_info.xlsx'); // 设置下载文件名
    document.body.appendChild(link);
    link.click(); // 触发下载
    document.body.removeChild(link); // 清理DOM
    URL.revokeObjectURL(fileURL); // 释放URL对象
    await ElMessage.success('导出成功')
  }else{
    ElMessage.error('导出失败')
  }
}

/**
 * 导入excel表格
 */
const handleImport = (res,file,fileList) => {
  if(!file.name.toLowerCase().endsWith('.xlsx')){
    ElMessage.error('请上传.xlsx类型的文件')
    return
  }
  if(res.status === 'success'){
    load()
    ElMessage.success('导入成功')
  }else{
    ElMessage.error(res.info)
  }
}
const getToken = () => {
  return localStorage.getItem('token')
}

/**
 * 任命队长
 * 实现原理：为该队员添加一个后台账号，如果后台已经有账号了，则将role值改为3
 */
const appointCaptain = async(userInfo) => {
  ElMessageBox.confirm(
    '确定要任命选中的队员为队长吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
  //解构userInfo成adminInfo
  const { name,userId } = userInfo
  const adminInfo = { userName: name,role: 3,account: userId}
  const res = await adminAddService(adminInfo)
  if(res.data.status === 'success'){
  }else{//如果后台已经有账号了，则将role值改为3
    //根据userId查询admin信息
    const adminRes = await adminSelectService(userId)
    const admin = adminRes.data.data.list[0]
    admin.role = 3
    await adminModifyService(admin)
    // ElMessage.error(res.data.info)
  }
  ElMessage.success('任命成功')
  await load()
})
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消任命',
      })
    })
}


/**
 * 取消任命队长
 * 实现原理：为该队员添加一个后台账号
 */
 const cancelCaptain = async(userId) => {
  ElMessageBox.confirm(
    '确定要取消任命选中的队长吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
  //根绝userId查询admin信息
  const adminRes = await adminSelectService(userId)
  const adminInfo = adminRes.data.data.list[0]
  adminInfo.role = 4
  // console.log(adminInfo)
  const res = await adminModifyService(adminInfo)
  // console.log(res.data)
  if(res.data.status === 'success'){
    ElMessage.success('取消任命成功')
    await load()
  }else{
    ElMessage.error(res.data.info)
  }
})
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消任命失败',
      })
    })
}
</script>

<template>
<!--  模态窗口-->
<!--  修改成员信息模态窗口-->
  <div class="modify-modal" v-show="showModifyModal">
    <div class="modify-form">
      <div class="close-btn" @click="showModifyModal=false">&times;</div>
      <h1 style="text-align: center;font-size: 30px">修改队员信息</h1>
      <el-form :model="userForm" label-width="auto" style="max-width: 600px;margin: auto;margin-top: 50px">
        <el-form-item label="姓名">
          <el-input v-model="userForm.name" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="userForm.gender">
            <el-radio :value="0">未知</el-radio>
            <el-radio :value="1">男</el-radio>
            <el-radio :value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userForm.telphoneNumber" />
        </el-form-item>
<!--        <el-form-item label="身份证">-->
<!--          <el-input v-model="userForm.idCard" />-->
<!--        </el-form-item>-->
        <el-form-item style="float: right">
          <el-button type="primary" @click="handleEdit">修改</el-button>
          <el-button @click="showModifyModal=false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
<!--  添加成员模态窗口-->
  <div class="modify-modal" v-show="showAddModal">
    <div class="modify-form">
      <div class="close-btn" @click="showAddModal=false">&times;</div>
      <h1 style="text-align: center;font-size: 30px">添加队员</h1>
      <el-form :model="userAddForm" ref="ruleFormRef" :rules="rules" label-width="auto" style="max-width: 600px;margin: auto;margin-top: 50px">
        <el-form-item label="学号" prop="userId">
          <el-input v-model="userAddForm.userId" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userAddForm.name" />
        </el-form-item>
<!--        <el-form-item label="年级" prop="grade">-->
<!--          <el-input v-model="userAddForm.grade" />-->
<!--        </el-form-item>-->
        <el-form-item label="性别">
          <el-radio-group v-model="userAddForm.gender">
            <el-radio value="0">未知</el-radio>
            <el-radio value="1">男</el-radio>
            <el-radio value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userAddForm.email" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userAddForm.telphoneNumber" />
        </el-form-item>
<!--        <el-form-item label="身份证">-->
<!--          <el-input v-model="userAddForm.idCard" />-->
<!--        </el-form-item>-->
        <el-form-item style="float: right">
          <el-button type="primary" @click="addUserInfo(ruleFormRef)">添加</el-button>
          <el-button @click="showAddModal=false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>


  <div>
<!--    功能按钮-->
    <el-card style="width: 34%;margin-bottom: 30px;float: left">
      <el-button @click="openAddModal" type="primary">添加成员</el-button>
      <el-button @click="opendeleteAllModal" type="danger">批量删除</el-button>
      <el-button @click="exportExcel" type="success">导出Excel</el-button>
      <el-upload style="display: inline-block;margin-left: 12px"
                 :show-file-list="false"
                 :on-success="handleImport"
                 accept=".xlsx,.xls"
                 :headers="{token: getToken()}"
      :action="axios.defaults.baseURL + '/userInfo/uploadExcel'">
        <el-button type="success">导入Excel</el-button>
      </el-upload>
<!--        >-->
    </el-card>
<!--    搜索框-->
    <el-card class="member-search">
      <span><h2>学号：</h2></span>
      <input v-model="userIdInput" @keyup.enter.native="load">
      <span style="margin-left: 10px"><h2>姓名：</h2></span>
      <input v-model="nameInput" @keyup.enter.native="load">
      <span style="margin-left: 10px"><h2>年级：</h2></span>
      <input v-model="gradeInput" @keyup.enter.native="load" style="border-right: none;">
      <el-button type="warning" @click="load">搜索</el-button>
    </el-card>
  </div>
  <div>
    <el-table
      ref="multipleTableRef"
      :data="userInfo"
      stripe
      style="width: 100%;margin-top: 30px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column property="userId" label="学号" width="130"/>
      <el-table-column property="name" label="姓名" width="80" />
      <el-table-column property="gender" label="性别" width="70">
        <template #default="scope">
          {{ formatGender(scope.row.gender) }}
        </template>
      </el-table-column>
      <el-table-column property="telphoneNumber" label="手机号" width="120" />
      <el-table-column property="grade" label="年级" width="70" />
      <el-table-column property="idCard" label="身份证" />
      <el-table-column property="createTime" label="入队时间" width="170"/>
      <el-table-column property="lastLoginTime" label="上次登录时间" width="170"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button v-if="(adminStore.admin.role == 1 || adminStore.admin.role == 2) && scope.row.role != 3" type="success" size="small" @click="appointCaptain(scope.row)">
            任命队长
          </el-button>
          <el-button v-if="(adminStore.admin.role == 1 || adminStore.admin.role == 2) && scope.row.role == 3" type="warning" size="small" @click="cancelCaptain(scope.row.userId)">
            取消任命
          </el-button>
          <el-button type="info" size="small" @click="openModifyModal(scope.row)">
            修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="openDeleteModal(scope.row.userId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
<!--    分页组件-->
    <el-card style="margin-top: 20px;float: right;">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[2, 5, 10, 20]"
          size="large"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

  </div>
</template>


<style scoped>
/*模态窗口样式*/
.modify-modal{
  position: fixed;
  z-index: 10;
  left: 0;top: 0;
  width: 100%;height: 100%;
  background: black;
  opacity: .95;
}
/*模态窗口表格样式*/
.modify-form{
  background-color: #ffffff;
  margin: 10% auto; /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  z-index: 10;
  border-radius: 10%;
  width: 30%; /* Could be more or less, depending on screen size */
}
.close-btn {
  cursor: pointer;
  color: #000000;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
/*搜索样式*/
.member-search{
  width: 64%;
  float: right
}
.member-search span{
  float: left;
}
.member-search input{
  float: left;
  height: 25px;
  border: solid 2px;
  margin-top: 2px;
}
/*表头样式*/
:deep() th.el-table__cell{
  color: black;
  font-size: 20px;
}
</style>
